<?php
require_once( 'Zend/Controller/Action.php');
require_once( 'Zend/Db.php' );
require_once( 'Zend/Db/Table.php' );
require_once( 'Zend/Db/Table/Abstract.php' );
require_once( 'models/Paciente.php');
require_once( 'models/Es_Medico.php');
require_once( 'models/Revisa.php');
require_once( 'models/Consulta.php');
require_once( 'modules/default/Form/Form.php');
require_once( 'IndexController.php');
require_once( 'Zend/Exception.php');
require_once( 'InitController.php');
require_once( 'Zend/Dojo.php');
require_once( 'Zend/Dojo/Form.php');
require_once( 'Zend/Dojo/Form/Element/DateTextBox.php');
require_once( 'Zend/Dojo/View/Helper/DateTextBox.php');
require_once( 'Zend/Dojo/View/Helper/Dijit.php');
require_once( 'Zend/Dojo/View/Helper/Dojo/Container.php');
require_once( 'Zend/Dojo/Form/Decorator/DijitElement.php');
require_once( 'Zend/View.php');



class TurnoController extends InitController {
       
   
    public function indexAction()
    {
    	$this->view->title = 'Medisoft - Nuevo Turno';  
    	$this->view->date = $this->getmedsForm();
       
    }
   
        public function timeAction()
    {
    	$this->view->title = 'Medisoft - Nuevo Turno';
    	$request = $this->getRequest();

        // Check if we have a POST request
        if ($request->isPost()) {
    	
        	$med = $_POST['medico'];
        	$date = $_POST['date'];
        	$data = array('medico'=>$med, 'date'=>$date);
        	$this->view->medicos = $this->getmedsForm();
        	$this->view->medicos->populate($data);
        	$this->view->time = $this->gettimeForm($med,$date);

        }
        $this->view->medicos = $this->getmedsForm();

        return $this->render('index');
    }
   
	public function insertAction()
    {
    	$this->view->title = 'Medisoft - Nuevo Turno';
    	$request = $this->getRequest();

        // Check if we have a POST request
        if ($request->isPost()) {
    	
    		$veriftime = $_POST['time'];
    		if ($veriftime != '')
    		{
    	
    			$paciente = new PACIENTE;
    			$paciente->dni = $_POST['dni'];
    			if ($paciente->pacexists() == 1)
    			{
               
        			$revisa = new REVISA();
        			$consulta = new CONSULTA;
       
        			$revisa->esdni = $_POST['medico'];
                	$revisa->pdni = $_POST['dni'];
                	$consulta->fechayhora = $_POST['time'];
                	$consulta->obs = "Turno";
       
                	$consultares = $consulta->insConsulta();
                	if ($consultares == false)
                	{
                        $this->view->message = 'No se pudo Ingresar el turno'. $consultares;
                	}
                	else
                	{
               
                	$revisares = $revisa->insRevisa();
                	if ($revisares == false)
                        {
                	        $this->view->message = 'No se pudo Ingresar el turno';
                    }
                    else
                    {
                    	$this->view->message = 'Turno Ingresado con Éxito!';
                        $this->view->fecha = $consulta->fechayhora;
                        $this->view->medico = $revisa->esdni;
                        $this->view->paciente = $revisa->pdni;
                    }
                }
    		}
    		else
    		{
    			$this->view->message = 'No se pudo Ingresar el turno. El paciente no existe.';
    		}
    	}
    	else
    		{
    			$this->view->message = 'No se pudo Ingresar el turno. Debe ingresar un horario válido.';
    		}
        } 
        $this->view->date = $this->getmedsForm();
        return $this->render('index');
       
    }
   
        private function getmedsForm() {
                $form = new Zend_Form();
                $form->setAction("/index.php/turno/time")->setMethod('post');
               
                $table = new ES_MEDICO();
                $this->view->meds = $table->listallMedicos();
               
                $medarray = array();
                foreach ($this->view->meds as $meds)
                {
                        $medarray[$meds->PEDNI] = $meds->PENOMBRE. " ". $meds->APELLIDO . " (" . $meds->PEDNI . ")" ;
                       // $medarray[$meds->PEDNI] = $meds->PEDNI . "   " . $meds->MESPECIALIDAD;
                }
                $date = new Zend_Dojo_Form_Element_DateTextBox('date');
                $date->setLabel('Seleccione una fecha');
                $date->setInvalidMessage('La fecha ingresada es inválida');
                $date->setPromptMessage('mm-dd-yyyy');
                $date->setRequired(true);
		         	

                $medsname = $form->createElement('select', 'medico', array('label' => 'Medico',  'value' => 'medico', 'multiOptions' => $medarray));
               
                $submit = $form->createElement('submit', 'seleccionar', array('label' => 'Seleccionar'));
               
                // Add elements to form:
                $aux = $form->addElement($date)
                         	->addElement($medsname)
                     		//->addElement('hidden', 'auxdni', array('values' => ''))
                     		->addElement($submit);
        return $form;
    }
   
        private function gettimeForm($medico, $fechain) {
               
                $flag = 0;
                
               
                $table = new CONSULTA();
                $diatrab = new DIAS_DE_TRABAJO();
                $date = new Zend_Date($fechain, 'yyyy-MM-dd');
                $diatrab->dni = $medico;
                $adian = $date->get(Zend_Date::WEEKDAY_DIGIT);
                switch ($adian){
                        case 0: $diatrab->adia = 'domingo';
                                        break;
                        case 1: $diatrab->adia = 'lunes';
                                        break;
                        case 2: $diatrab->adia = 'martes';
                                        break;
                        case 3: $diatrab->adia = 'miercoles';
                                        break;
                        case 4: $diatrab->adia = 'jueves';
                                        break;
                        case 5: $diatrab->adia = 'viernes';
                                        break;
                        case 6: $diatrab->adia = 'sabado';
                                        break;
                                       
                }
               
               
                $trabaja = $diatrab->trabajadia();
                if ($trabaja == 1)
                {
               
                	$diatrab->medico = $medico;
                	$desdehasta = $diatrab->desdehasta();
               	
               	 	foreach($desdehasta as $from)
               	 	{
                        $desde = $from->DESDE2;
                        $hasta = $from->HASTA2;
                	}
               

                	
                	$table->dni = $medico;
                	$timearray = array();
               
               
                	$date2 = new Zend_Date($desde);
                	$date3 = new Zend_Date($hasta);
               
               	 	$date->add($date2->get(Zend_Date::TIMES), Zend_Date::TIMES);
               
                	$date3->add('00:15:00', Zend_Date::TIMES);
                	if ($date2->compare($date3) == 0) {
                        $flag = 1;
               
                	}
               
                	$table->fechayhora = $date->get('YYYY-MM-dd HH:mm:ss');
               
                	$date2->add('00:15:00', Zend_Date::TIMES);
               
                	for ($i = 0;$flag == 0; $i++)
                	{
                       
                        $date2->add('00:15:00', Zend_Date::TIMES);
                        if ($date2->compare($date3) == 0) {
                                $flag = 1;
                       
                    	}
                    	$this->view->turnook = $table->turnolibre();
                    	if ($this->view->turnook == 1)
                    	{
                                $timearray[$table->fechayhora] = $table->fechayhora;
                    	}
                       
                        $date->add('00:15:00', Zend_Date::TIMES);
                        $table->fechayhora = $date->get('YYYY-MM-dd HH:mm:ss');
                        
                        $form = new Zend_Form();
                		$form->setAction("/index.php/turno/insert")->setMethod('post');
                		
                		$time = $form->createElement('select', 'time', array('label' => 'Time',  'value' => '', 'multiOptions' => $timearray));
                		$pacdni = $form->createElement('text', 'dni', array('label' => 'DNI Paciente'));
                		$pacdni->addValidator('alnum')
                         ->addValidator('regex', false, array('/^[0-9]+/'))
                         ->addValidator('stringLength', false, array(1, 10))
                         ->setRequired(true);
                         
                $submit = $form->createElement('submit', 'seleccionar', array('label' => 'Seleccionar'));
               
                // Add elements to form:
                $form->addElement($time)
                     ->addElement($pacdni)
                     ->addElement($submit)
                     ->addElement ('hidden', 'medico', array('value' => $medico));
                       
                	}
                }
                else {
                        //$timearray = array(''=>'');
                        $this->view->message = "El médico seleccionado no trabaja ese día";
                        $form = '';
                }
               
               
                
        return $form;
    }
    
    public function lturnosAction(){
    	Zend_Loader::loadClass('Consulta', 'models');
    	
    	$this->view->turnoform = $this->getturnoForm();
    	
    	$turnos = new CONSULTA;
    	$request = $this->getRequest();

        // Check if we have a POST request
        if ($request->isPost()) {
        	
    		$turnos->dni = $_POST['dni'];
    		$this->view->turnos = $turnos->listConsultas();
    	}
    	else
    	{
    		$this->view->turnos = $turnos->listallConsultas();
    		
    	}
    		
    		
    		
    	return $this->render('lturnos');
    }
    
private function getturnoForm() {
                $form = new Zend_Form();
                $form->setAction("/index.php/turno/lturnos")->setMethod('post');
               
                $pacdni = $form->createElement('text', 'dni', array('label' => 'DNI Paciente'));
                		$pacdni->addValidator('alnum')
                         ->addValidator('regex', false, array('/^[0-9]+/'))
                         //->addValidator('stringLength', false, array(1, 10))
                         ->setRequired(true);
		         
		         $pacsub = $form->createElement('submit', 'ingresar', array('label' => "Ingresar"));
		         
		         $form->addElement($pacdni)
		         ->addElement($pacsub);
		         return $form;	
    }
    
	   
}


?>
